<template>
  <div class="app-container">
    <!-- <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="输入搜索：">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="角色名称" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card> -->
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>角色列表</span>
      <el-button
        size="mini"
        class="btn-add"
        @click="handleAdd()"
        style="margin-left: 20px"
        >添加</el-button
      >
    </el-card>
    <div class="table-container">
      <el-table
        ref="roleTable"
        :data="list"
        style="width: 100%"
        v-loading="listLoading"
        border
      >
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="角色名称" align="center">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="描述" align="center">
          <template slot-scope="scope">{{ scope.row.description }}</template>
        </el-table-column>
        <el-table-column label="用户数" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.adminCount }}</template>
        </el-table-column>
        <el-table-column label="添加时间" width="160" align="center">
          <template slot-scope="scope">{{ scope.row.createTime }}</template>
        </el-table-column>
        <!-- <el-table-column label="是否启用" width="140" align="center">
          <template slot-scope="scope">
            <el-switch
           active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="0"
              :inactive-value="1"
            v-model="scope.row.status"
             
              
            >
            </el-switch>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="160" align="center">
          <template slot-scope="scope">
            <el-row>
              <el-button
                size="mini"
                type="text"
                @click="handleSelectMenu(scope.$index, scope.row)"
                >分配菜单
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleSelectResource(scope.$index, scope.row)"
                >分配资源
              </el-button>
            </el-row>
            <el-row>
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.$index, scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.$index, scope.row)"
                >删除
              </el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15]"
        :total="total">
      </el-pagination>
    </div> -->
    <el-dialog
      :title="isEdit ? '编辑角色' : '添加角色'"
      :visible.sync="dialogVisible"
      width="40%"
       
    >
      <el-form :model="role" ref="roleForm" label-width="150px" size="small">
        <el-form-item label="角色名称：">
          <el-input v-model="role.name" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="描述：">
          <el-input
            v-model="role.description"
            type="textarea"
            :rows="5"
            style="width: 250px"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否启用：">
          <el-radio-group v-model="role.status">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button   type="primary" @click="handleDialogConfirm()" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配菜单 -->
    <el-dialog   title="分配菜单" :visible.sync="menuDialogVisible" width="40%">
      <el-tree
      v-loading="loading"
        :data="men_data"
        show-checkbox
        node-key="id"
        ref="treeref"
         :default-checked-keys="expanded"
         :default-expanded-keys="expanded"
        :props="label"
       @check-change="getCheckedKeys"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="menuDialogVisible = false" size="small"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="tree()"
          size="small"
          :loading="loading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import {fetchList,createRole,updateRole,updateStatus,deleteRole} from '@/api/role';
// import {formatDate} from '@/utils/date';
import { getRoleList, getAuthMenu,assignMenu ,editRole,getRoleMenu} from "@/api/user_list";
const defaultListQuery = {
  pageNum: 1,
  pageSize: 5,
  keyword: null,
};
const defaultRole = {
  id: null,
  name: null,
  description: null,
  adminCount: 0,
  status: 1,
};
export default {
  name: "roleList",
  data() {
    return {
      value:true,
      loading: false,
      expanded:[],
      role_id:null,
      men_data:{},
      menuDialogVisible: false,
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      role: Object.assign({}, defaultRole),
      isEdit: false,
    };
  },
  created() {
    this.getList();
  },
  filters: {
    formatDateTime(time) {
      if (time == null || time === "") {
        return "N/A";
      }
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
  },
  methods: {
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.role = Object.assign({}, defaultRole);
    },
    handleStatusChange(index, row) {
      this.$confirm("是否要修改该状态?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateStatus(row.id, { status: row.status }).then((response) => {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消修改",
          });
          this.getList();
        });
    },
    handleDelete(index, row) {
      this.$confirm("是否要删除该角色?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ids = [];
        ids.push(row.id);
        let params = new URLSearchParams();
        params.append("ids", ids);
        deleteRole(params).then((response) => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        });
      });
    },
    handleUpdate(index, row) {
      this.dialogVisible = true;
      this.isEdit = true;
      this.role = Object.assign({}, row);
      
    },
    handleDialogConfirm() {
       this.loading=true
      this.$confirm("是否要确认?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (this.isEdit) {
          console.log(this.role);
         
          editRole( this.role).then((response) => {
            this.$message({
              message: "修改成功！",
              type: "success",
            });
            this.loading=false
            console.log(response);
            this.dialogVisible = false;
            this.getList();
          });
        } else {
          createRole(this.role).then((response) => {
            this.$message({
              message: "添加成功！",
              type: "success",
            });
            this.dialogVisible = false;
            this.getList();
          });
        }
      });
    },
    handleSelectMenu(index, row) {
      this.menuDialogVisible = true;
      this.role_id=row.id
      console.log(this.role_id)
      this.getMenuList();
      this.getRoleMenu()

    },
    handleSelectResource(index, row) {
      this.$router.push({
        path: "/ums/allocResource",
        query: { roleId: row.id },
      });
    },
    getList() {
      this.listLoading = true;
      getRoleList().then((response) => {
        this.listLoading = false;
        this.list = response.data.data;
        // this.total = response.data.total;
        console.log(this.list);
      });
    },
    //获取全部菜单
    getMenuList() {
      
      getAuthMenu().then((response) => {
        // this.total = response.data.total;
        console.log(response);
        this.men_data=response.data.data 
        let arr=[]
        this.men_data=response.data.data.map(item=>{
         
          return {
            id:item.id,
            label:item.title,
            children:item.children.map(res=>{
              return {
                id:res.id,
                label:res.title,
              }
            })
          }
         
        })
        console.log(this.men_data)
      });
    },
     tree(){
       const keys=[
          ...this.$refs.treeref.getCheckedKeys(),
           ...this.$refs.treeref.getHalfCheckedKeys()
       ]
       console.log(keys)
       //分配菜单
       this.loading=true
        let params = new URLSearchParams();
        params.append("roleId", this.role_id);
        params.append("ids", keys);
        assignMenu(params).then((response) => {
          console.log(response)
          this.$message({
            type: "success",
            message: "分配成功!",
          });
          this.loading=false
          this.menuDialogVisible = false;
          // this.getList();
        });
     },
     //获取角色已分配的菜单
      getRoleMenu(){
        this.loading=true;
        let params = new URLSearchParams();
        params.append("roleId", this.role_id);
        getRoleMenu(params).then((response) => {
          this.loading=false;
          console.log(response)
          this.expanded=response.data.data
        
        });
      },

  },
};
</script>
<style></style>
